package com.example.demo.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.demo.bean.currency.LoginResponse;
import com.example.demo.bean.currency.Sucess;
import com.example.demo.bean.login.LoginBean;
import com.example.demo.bean.login.LoginPamas;
import com.example.demo.bean.user.UserBean;
import com.example.demo.mapper.login.LoginMapper;
import com.example.demo.mapper.login.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@RequestMapping("/api")
@RestController
@SpringBootApplication
public class Login {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private UserMapper userMapper;
    @PostMapping("login")
    public Sucess login (@RequestBody LoginPamas loginBean, HttpServletRequest request){
        QueryWrapper<LoginBean> wrapper = new QueryWrapper<LoginBean>();
        String headerValue = request.getHeader("token"); // 替换"Header-Name"为你要获取的实际请求头名称
        wrapper.eq("username",loginBean.getUsername());
        wrapper.eq("password",loginBean.getPassword());

        List<LoginBean> userList = loginMapper.selectList(wrapper);

        Sucess sucess = new Sucess<LoginResponse>();
        if (userList.isEmpty()) {
            sucess.setCode(100);
            return sucess;
        }
        LoginBean user = userList.get(0);
        // 登录成功后，生成并返回令牌
        String token = generateToken(userList.get(0)); // 假设你有一个生成令牌的方法

        // 更新用户表中的token字段
        updateUserToken(user.getId(), token);
        LoginResponse LoginResponse = new LoginResponse();
        LoginResponse.setToken(token);
        sucess.setData(LoginResponse);

        return  sucess;
    }
    // 新增方法用于更新用户token
    private void updateUserToken(Long userId, String token) {
        UserBean updateBean = new UserBean();
        updateBean.setId(userId);
        updateBean.setToken(token); // 假设LoginBean类中有一个setToken方法用于设置token
        userMapper.updateById(updateBean); // 使用MyBatis Plus的updateById方法更新数据库
    }

    // 示例生成令牌的方法
    private String generateToken(LoginBean user) {
        return UUID.randomUUID().toString();
        // 实现令牌生成逻辑
    }
}
